package com.mingqijia.gassafety.job.job.mbp;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.mingqijia.gassafety.db.entity.FieldTemplate;
import com.mingqijia.gassafety.db.entity.vo.UserServiceComboVO;
import com.mingqijia.gassafety.db.mapper.FieldTemplateMapper;
import com.mingqijia.gassafety.db.mapper.ServiceComboDetailMapper;
import com.mingqijia.gassafety.db.mapper.ServiceComboOrderMapper;
import com.mingqijia.gassafety.job.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.job.request.sk.ConsoleSkRecordsRequest;
import com.mingqijia.gassafety.job.response.sk.ConsoleSkRecordsList;
import com.mingqijia.gassafety.job.response.sk.ConsoleSkRecordsResponse;
import com.mingqijia.gassafety.shared.constant.UrlConst;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author: duanhongxiang
 * @Desc:
 * @create: 2024-09-05 13:50
 **/
@Component
@Slf4j
public class WorkOrderAutoGenJob {

    @Value("${gassafety.alarm.storage.period:3}") //处理存蓄期默认3小时
    private Integer alarmStoragePeriod;

    @Value(value = "${gassafety.business.api.url}")
    public String webserver;

    @Autowired
    FieldTemplateMapper fieldTemplateMapper;

    @Autowired
    ConsoleSkFeignClient consoleSkFeignClient;

    @Autowired
    ServiceComboOrderMapper serviceComboOrderMapper;

    @Autowired
    ServiceComboDetailMapper serviceComboDetailMapper;



    @XxlJob("workOrderAutoGen")
    public ReturnT<String> workOrderAutoGen(String param) {
        XxlJobLogger.log("XXLJOB-workOrderAutoGen start..." );
        log.info("workOrderAutoGen ---- start:");
        try {
            workOrderAutoGenHandle(param);
        } catch (Exception e) {
            log.info("workOrderStatus-error:{}", e);
        }

        XxlJobLogger.log("XXLJOB-workOrderAutoGen end..." );
        return ReturnT.SUCCESS;
    }

    private void workOrderAutoGenHandle(String param){
        List<FieldTemplate> fieldTemplates = fieldTemplateMapper.getSkWorkSystemTypeAuto();
        log.info("fieldTemplates:{}",JSONObject.toJSONString(fieldTemplates));
        if (null == fieldTemplates || fieldTemplates.isEmpty()) {
            log.info("fieldTemplates is null");
            return;
        }
        for (FieldTemplate fieldTemplate:fieldTemplates){
            try {
                String spId = fieldTemplate.getSpId();
                ConsoleSkRecordsRequest consoleSkRecordsRequest = new ConsoleSkRecordsRequest();
                consoleSkRecordsRequest.setSpId(spId);
                consoleSkRecordsRequest.setDealStatus("0");
                Date currDate = new Date();

                String alarmEndTime = DateUtils.format(currDate, "yyyy-MM-dd HH:mm:ss");
                String alarmBeginTime = DateUtil.offsetHour(new Date(), -alarmStoragePeriod).toString("yyyy-MM-dd HH:mm:ss");

                if (!StringUtils.isEmpty(param)){
                    consoleSkRecordsRequest.setId(param);
                }else{
                    consoleSkRecordsRequest.setAlarmStartTime(alarmBeginTime);
                    consoleSkRecordsRequest.setAlarmEndTime(alarmEndTime);
                }
                consoleSkRecordsRequest.setPage(1);
                consoleSkRecordsRequest.setPageSize(500);;
                log.info("alarmSOSRecords-response:{}", JSONObject.toJSONString(consoleSkRecordsRequest));
                ConsoleSkRecordsResponse skResp = consoleSkFeignClient.alarmSOSRecords(consoleSkRecordsRequest);
                log.info("alarmSOSRecords-response:{}", JSONObject.toJSONString(skResp));

                if (!ObjectUtils.isEmpty(skResp) && 0 == skResp.getCode() && null != skResp.getData() && null != skResp.getData().getList() &&
                        !skResp.getData().getList().isEmpty()) {
                   for (ConsoleSkRecordsList skRecord:skResp.getData().getList()){
                       String code = String.valueOf(skRecord.getDeviceType());
                       int userId = Integer.parseInt(skRecord.getUserId());
                       List<UserServiceComboVO> userServiceComboVOList = serviceComboDetailMapper.getUserServiceCombo(code, userId);
                       if (null == userServiceComboVOList || userServiceComboVOList.isEmpty()) {
                          continue;
                       }
                       UserServiceComboVO userServiceComboVO = userServiceComboVOList.get(0);

                       JSONObject jsonData = new JSONObject();
                       jsonData.put("skData",skRecord);
                       jsonData.put("userServiceCombo",userServiceComboVO);
                       String url = webserver + UrlConst.SK_ORDER_AUTO_CREATE.getUrl();
                       String jsonStr = JSONObject.toJSONString(jsonData);
                       log.info("智慧厨房工单自动创建参数:{}",jsonStr);
                       String body = HttpUtil.getBody(jsonStr, url, spId);
                       log.info("智慧厨房工单自动创建结果:{}",body);
                   }
                }
            }catch (Exception e){

            }

        }
    }
}
